// pages/memo/memo.js
const app = getApp();

Page({
  data: {
    currentRoomId: null,
    roomInput: "",
    recentRooms: [],
    memos: [],
    filteredMemos: [],
    searchQuery: "",
    viewMode: "all", // all, memo, task
    loading: false,
    showMemoModal: false,
    isEditing: false,
    activeMemo: null,
    isSaveDisabled: true, // 新增：控制保存按钮的禁用状态
    newTaskContent: "", // 用于任务清单的新任务内容
    stats: {
      totalMemos: 0,
      taskListCount: 0,
      completionRate: 0,
    },
  },

  // 空操作函数，用于阻止事件冒泡
  noop() {},

  onLoad() {
    this.loadCurrentRoom();
    this.loadRecentRooms();
  },

  // 任务排序函数：未完成的在前，已完成的在后
  sortTasks(tasks) {
    if (!tasks || !Array.isArray(tasks)) return [];
    return tasks.sort((a, b) => {
      // 未完成的任务排在前面
      if (a.is_completed !== b.is_completed) {
        return a.is_completed ? 1 : -1;
      }
      // 相同状态按创建时间或order_index排序
      return (a.order_index || 0) - (b.order_index || 0);
    });
  },

  onShow() {
    if (this.data.currentRoomId) {
      this.loadMemos();
    }
  },

  // --- 房间管理 ---
  loadCurrentRoom() {
    const roomId = app.getCurrentRoomId();
    if (roomId) {
      this.setData({ currentRoomId: roomId });
      this.loadMemos();
    }
  },

  async loadRecentRooms() {
    try {
      const response = await app.request({ url: "/api/memo/rooms" });
      this.setData({ recentRooms: response.data || [] });
    } catch (error) {
      console.error("加载最近房间失败:", error);
    }
  },

  onRoomInputChange(e) {
    this.setData({ roomInput: e.detail.value });
  },

  async enterRoom() {
    const roomId = this.data.roomInput.trim();
    if (!roomId) {
      return app.showToast("请输入房间号码");
    }

    app.showLoading("进入房间中...");
    try {
      await app.request({
        url: "/api/memo/room/access",
        method: "POST",
        data: { roomId },
      });
      app.setCurrentRoomId(roomId);
      this.setData({ currentRoomId: roomId, roomInput: "" });
      this.loadMemos();
      this.loadRecentRooms();
    } catch (error) {
      app.showToast("进入房间失败");
      console.error("进入房间失败:", error);
    } finally {
      app.hideLoading();
    }
  },

  selectRoom(e) {
    const roomId = e.currentTarget.dataset.roomId;
    app.setCurrentRoomId(roomId);
    this.setData({ currentRoomId: roomId });
    this.loadMemos();
  },

  showRoomSelector() {
    this.setData({ currentRoomId: null });
    app.setCurrentRoomId(null);
  },

  // --- 备忘录数据处理 ---
  async loadMemos() {
    if (!this.data.currentRoomId) return;
    this.setData({ loading: true });
    try {
      const response = await app.request({
        url: `/api/memo/items/${this.data.currentRoomId}`,
      });
      const memos = (response.data || []).map((memo) => {
        memo.formatted_date = this.formatDate(memo.updated_at);
        try {
          memo.tags =
            typeof memo.tags === "string" ? JSON.parse(memo.tags) : [];
        } catch {
          memo.tags = [];
        }
        if (!memo.is_task_list) {
          memo.preview_content = memo.content.substring(0, 100);
        }
        
        // 对任务进行排序：未完成的在前，已完成的在后
        if (memo.is_task_list && memo.tasks) {
          memo.tasks = this.sortTasks(memo.tasks);
        }
        
        return memo;
      });
      this.setData({ memos });
      this.filterMemos();
      this.calculateStats();
    } catch (error) {
      app.showToast("加载失败");
      console.error("加载备忘录失败:", error);
    } finally {
      this.setData({ loading: false });
    }
  },

  onSearchInput(e) {
    this.setData({ searchQuery: e.detail.value });
    this.filterMemos();
  },

  setViewMode(e) {
    this.setData({ viewMode: e.currentTarget.dataset.mode });
    this.filterMemos();
  },

  filterMemos() {
    const { memos, viewMode, searchQuery } = this.data;
    let filtered = [...memos];

    if (viewMode === "memo") filtered = filtered.filter((m) => !m.is_task_list);
    if (viewMode === "task") filtered = filtered.filter((m) => m.is_task_list);

    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(
        (m) =>
          m.title.toLowerCase().includes(query) ||
          m.content.toLowerCase().includes(query)
      );
    }
    this.setData({ filteredMemos: filtered });
  },

  calculateStats() {
    const memos = this.data.memos;
    const totalMemos = memos.filter((m) => !m.is_task_list).length;
    const taskListCount = memos.filter((m) => m.is_task_list).length;
    let totalTasks = 0,
      completedTasks = 0;

    memos.forEach((memo) => {
      if (memo.is_task_list && memo.tasks) {
        totalTasks += memo.tasks.length;
        completedTasks += memo.tasks.filter((t) => t.is_completed).length;
      }
    });
    const completionRate =
      totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0;
    this.setData({ stats: { totalMemos, taskListCount, completionRate } });
  },

  // --- 模态框与表单 ---
  showAddMemoModal() {
    this.setData({
      showMemoModal: true,
      isEditing: false,
      activeMemo: { title: "", content: "", is_task_list: false, tags: "" },
      isSaveDisabled: true,
    });
  },

  editMemo(e) {
    const memo = e.currentTarget.dataset.memo;
    const tagsStr = Array.isArray(memo.tags) ? memo.tags.join(" ") : "";
    // 对任务进行排序：未完成的在前，已完成的在后
    const sortedTasks = this.sortTasks(memo.tasks || []);
    this.setData({
      showMemoModal: true,
      isEditing: true,
      activeMemo: { ...memo, tags: tagsStr, tasks: sortedTasks },
      isSaveDisabled: false,
    });
  },

  hideAllModals() {
    this.setData({
      showMemoModal: false,
      isEditing: false,
      activeMemo: null,
      newTaskContent: "",
    });
  },

  onTitleInput(e) {
    const title = e.detail.value;
    this.setData({
      "activeMemo.title": title,
      isSaveDisabled: !title.trim(),
    });
  },

  onContentInput(e) {
    this.setData({ "activeMemo.content": e.detail.value });
  },

  onTagsInput(e) {
    this.setData({ "activeMemo.tags": e.detail.value });
  },

  // --- 任务清单编辑器事件 ---
  onNewTaskInput(e) {
    this.setData({ newTaskContent: e.detail.value });
  },

  async addTask() {
    const content = this.data.newTaskContent.trim();
    if (!content) return;

    const memo = this.data.activeMemo;
    if (!memo.uuid) {
      app.showToast("请先保存备忘录");
      return;
    }

    try {
      app.showLoading("添加中...");
      const result = await app.request({
        url: "/api/memo/task",
        method: "POST",
        data: {
          memoUuid: memo.uuid,
          content: content,
          orderIndex: (memo.tasks || []).length
        }
      });

      const tasks = memo.tasks || [];
      this.setData({
        "activeMemo.tasks": [...tasks, result.data],
        newTaskContent: "", // 清空输入框
      });
      app.showToast("添加成功", "success");
    } catch (error) {
      app.showToast("添加失败");
      console.error("添加任务失败:", error);
    } finally {
      app.hideLoading();
    }
  },

  async toggleTask(e) {
    const taskId = e.currentTarget.dataset.taskId;
    const task = this.data.activeMemo.tasks.find(t => t.id === taskId);
    if (!task) return;

    try {
      app.showLoading("更新中...");
      const result = await app.request({
        url: `/api/memo/task/${taskId}`,
        method: "PUT",
        data: {
          content: task.content,
          isCompleted: !task.is_completed,
          orderIndex: task.order_index || 0
        }
      });

      const tasks = this.data.activeMemo.tasks.map((task) => {
        if (task.id === taskId) {
          return { ...task, is_completed: !task.is_completed };
        }
        return task;
      });
      // 重新排序任务：未完成的在前，已完成的在后
      const sortedTasks = this.sortTasks(tasks);
      this.setData({ "activeMemo.tasks": sortedTasks });
      app.showToast("更新成功", "success");
    } catch (error) {
      app.showToast("更新失败");
      console.error("切换任务状态失败:", error);
    } finally {
      app.hideLoading();
    }
  },

  onTaskContentInput(e) {
    const taskId = e.currentTarget.dataset.taskId;
    const newContent = e.detail.value;
    const tasks = this.data.activeMemo.tasks.map((task) => {
      if (task.id === taskId) {
        return { ...task, content: newContent };
      }
      return task;
    });
    this.setData({ "activeMemo.tasks": tasks });
  },

  async deleteTask(e) {
    const taskId = e.currentTarget.dataset.taskId;
    const task = this.data.activeMemo.tasks.find(t => t.id === taskId);
    if (!task) return;

    try {
      app.showLoading("删除中...");
      const result = await app.request({
        url: `/api/memo/task/${taskId}`,
        method: "DELETE"
      });

      if (result.success) {
        // 从本地数据中移除任务
        const tasks = this.data.activeMemo.tasks.filter(
          (task) => task.id !== taskId
        );
        this.setData({ "activeMemo.tasks": tasks });
        app.showToast("删除成功", "success");
      } else {
        app.showToast("删除失败: " + result.message);
      }
    } catch (error) {
      console.error("删除任务失败:", error);
      app.showToast("删除失败");
    } finally {
      app.hideLoading();
    }
  },
  // -----------------------

  setMemoType(e) {
    const isTaskList = e.currentTarget.dataset.type === "task";
    this.setData({
      "activeMemo.is_task_list": isTaskList,
    });
    // 如果切换到任务清单且还没有 tasks 数组，初始化一个
    if (isTaskList && !this.data.activeMemo.tasks) {
      this.setData({
        "activeMemo.tasks": [],
      });
    }
  },

  async saveMemo() {
    const memo = { ...this.data.activeMemo };
    if (!memo.title || !memo.title.trim()) return app.showToast("标题不能为空");

    const tags =
      typeof memo.tags === "string" && memo.tags.trim()
        ? memo.tags.trim().split(/\s+/)
        : [];

    // 根据是否为任务清单，构造不同的 apiData
    const apiData = {
      title: memo.title,
      is_task_list: memo.is_task_list,
      tags: JSON.stringify(tags),
    };

    const isEditing = this.data.isEditing;

    if (memo.is_task_list) {
      if (isEditing) {
        apiData.tasks = memo.tasks.map((task) => {
          if (typeof task.id === "string" && task.id.startsWith("temp_")) {
            const { id, ...rest } = task;
            return rest;
          }
          return task;
        });
      } else {
        apiData.tasks = memo.tasks.map((task) => {
          const { id, ...rest } = task;
          return rest;
        });
      }
      apiData.content = "";
    } else {
      apiData.content = memo.content;
    }

    // web端是POST /api/memo/items，所有参数都在body里
    let url, method;
    if (isEditing) {
      url = `/api/memo/item/${memo.uuid}`;
      method = "PUT";
    } else {
      url = `/api/memo/items`;
      method = "POST";
      // 新建时需要补充roomId
      apiData.roomId = this.data.currentRoomId;
      // web端还会生成uuid，这里可选
      apiData.uuid = Date.now() + Math.random().toString(36).substr(2, 9);
    }

    app.showLoading(isEditing ? "保存中..." : "新建中...");
    try {
      await app.request({ url, method, data: apiData });
      this.hideAllModals();
      this.loadMemos();
    } catch (error) {
      app.showToast("保存失败");
      console.error("保存失败:", error);
    } finally {
      app.hideLoading();
    }
  },

  // --- 列表项操作 ---
  viewMemo(e) {
    this.editMemo(e);
  },

  async togglePin(e) {
    const memo = e.currentTarget.dataset.memo;
    try {
      // 置顶是更新操作的一部分，所以也使用 PUT /api/memo/:uuid
      await app.request({
        url: `/api/memo/item/${memo.uuid}`,
        method: "PUT",
        data: { is_pinned: !memo.is_pinned },
      });
      app.showToast(memo.is_pinned ? "取消置顶" : "置顶成功", "success");
      this.loadMemos();
    } catch (error) {
      app.showToast("操作失败");
      console.error("切换置顶失败:", error);
    }
  },

  deleteMemo(e) {
    const memo = e.currentTarget.dataset.memo;
    wx.showModal({
      title: "确认删除",
      content: `确定要删除“${memo.title}”吗？`,
      success: async (res) => {
        if (!res.confirm) return;
        app.showLoading("删除中...");
        try {
          await app.request({
            url: `/api/memo/item/${memo.uuid}`, // DELETE /api/memo/item/:uuid
            method: "DELETE",
          });
          this.loadMemos();
        } catch (error) {
          app.showToast("删除失败");
          console.error("删除失败:", error);
        } finally {
          app.hideLoading();
        }
      },
    });
  },

  // --- 工具函数 ---
  formatDate(dateString) {
    const seconds = Math.floor((new Date() - new Date(dateString)) / 1000);
    if (seconds < 60) return "刚刚";
    const minutes = Math.floor(seconds / 60);
    if (minutes < 60) return `${minutes}分钟前`;
    const hours = Math.floor(minutes / 60);
    if (hours < 24) return `${hours}小时前`;
    const days = Math.floor(hours / 24);
    return `${days}天前`;
  },
});
